/*
 * Copyright 2013-2018 Lilinfeng.
 *  
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.phei.netty.protocol.netty.codec;

import java.io.IOException;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import org.jboss.marshalling.Marshaller;
import org.jboss.marshalling.MarshallerFactory;
import org.jboss.marshalling.Marshalling;
import org.jboss.marshalling.MarshallingConfiguration;
import org.jboss.marshalling.Unmarshaller;

/**
 * @author Administrator
 * @date 2014年3月15日
 * @version 1.0
 */
public final class MarshallingCodecFactory {

	private static final int VERSION = 5;
	private static final Lock lock_foc = new ReentrantLock();
	private static final Lock lock_cof = new ReentrantLock();
	
	private static MarshallerFactory buidlerFactory(){
		
		lock_foc.lock();
		final MarshallerFactory  marshallerFactory;
		try {
			marshallerFactory = Marshalling.getProvidedMarshallerFactory("serial");
		} finally {
			lock_foc.unlock();
		}
		return marshallerFactory;
	}
	
	private static MarshallingConfiguration buidlerConfig(){
		lock_cof.lock();
		final MarshallingConfiguration configuration;
		try {
			configuration = new MarshallingConfiguration();
			configuration.setVersion(VERSION);
		} finally {
			lock_cof.unlock();
		}
		return configuration;
	}
	
	/**
	 * 创建Jboss Marshaller
	 * 
	 */
	protected static Marshaller buildMarshalling() throws IOException {
		 
		Marshaller marshaller = buidlerFactory().createMarshaller(buidlerConfig());
		return marshaller;
	}

	/**
	 * 创建Jboss Unmarshaller
	 * 
	 */
	protected static Unmarshaller buildUnMarshalling() throws IOException { 
		final Unmarshaller unmarshaller = buidlerFactory().createUnmarshaller(buidlerConfig());
		return unmarshaller;
	}
	 
}
